define(['../models/PDFDocument',
		'../models/PDFPage',
		'../models/PDFDocProperties',
		'../PDFConfig'], function(PDFDocument, PDFPage, PDFDocProperties, PDFConfig) {
		'use strict';
		var PDFDocService = {};
		var _pdfDoc = null;

		function _makeUrl() {
			var url = PDFConfig.baseUrl + PDFConfig.s3Key + "/PagesInfo_form";
			return url;
		}

		function _createPDFDoc(docInfo) {
			try {
				_pdfDoc = new PDFDocument(docInfo.doctype);
				_pdfDoc.pageCount = docInfo.PageCount;

				var i = 0;				
				$.each(docInfo.PagesInfo, function(i, pageInfo) {
					var pdfPage = new PDFPage(pageInfo);
					pdfPage.pageIndex = i++;
					_pdfDoc.addPage(pdfPage);
				});

				if (docInfo.dppinfo && docInfo.dppinfo.ppt) {
					var pDocProperties = new PDFDocProperties(docInfo.dppinfo.ppt);
					_pdfDoc.setDocProperties(pDocProperties);
				} else
					_pdfDoc.setDocProperties(null);					
			} catch (ex) {
				console.error(ex);				
			}

			return _pdfDoc;
		}


		function _makePageImgUrl(page) {
			var url = PDFConfig.baseUrl + PDFConfig.s3Key + "/page_" + page.pageIndex + '_zoom_100_1';
			return url;
		}

		function _loadDocument() {		
			return $.get(_makeUrl()).then(function(data){							
				return _createPDFDoc($.parseJSON(data));
			});		
		}

		function _loadPage(page) {
			var imgUrl = _makePageImgUrl(page);		
			return $.get(imgUrl).then(function(data) {
				page.imageUrl = imgUrl;
				page.isLoaded = true;
				return page;
			});			
		}


		PDFDocService.getManifest = function() {};
		PDFDocService.getPDFDoc = function() {
			//如果文档未加载，就执行加载过程
			if (!_pdfDoc) {
				return _loadDocument();
			} else {
				return $.when(_pdfDoc);
			}
		};

		PDFDocService.loadPDFPage = function(page) {
			if (!page.isLoaded) {
				return _loadPage(page);
			} else {
				return Promise.resolve(page);
			}
		};

		return PDFDocService;
	}
);